<?php

    namespace App\Http\Controllers\V1;

    use App\Dictionary\ErrorCode;
    use App\Http\Controllers\Controller;
    use App\User;
    use Carbon\Carbon;
    use Dotenv\Validator;
    use Illuminate\Http\Request;
    use Illuminate\Support\Facades\Auth;

    class AuthController extends Controller
    {
        //
        /**
         * 创建用户
         *
         * @param Request $request
         * signUp
         * author: walker
         * Date: 2019/11/18
         * Time: 19:22
         * Note:
         */
        public function signUp(Request $request)
        {
            $request->validate([
                                   'mobile'    => 'required|string',
                                   'email'     => 'required|string|email|unique:users',
                                   'password'  => 'required|string',
                                   'nick_name' => 'required',
                               ]);
            $user = new User([
                                 'mobile'   => $request->mobile,
                                 'email'    => $request->email,
                                 'nick_name'=>$request->nick_name,
                                 'password' => bcrypt($request->password),
                             ]);
            $user->save();
            ajaxReturn(200, '创建用户成功');
        }

        /**
         * 登录获取token
         *
         * @param Request $request
         * signIn
         * author: walker
         * Date: 2019/11/19
         * Time: 9:14
         * Note:
         */
        public function signIn(Request $request)
        {
            $email    = $request->input('mobile');
            $password = $request->input('password');
            if (empty($email) || empty($password)){
                ajaxReturn(4001, ErrorCode::$common[4001]);
            }
            $credentials = request(['mobile', 'password']);
            if ( !Auth::attempt($credentials)){
                ajaxReturn(4001, '该用户不存在');
            }
            $user        = $request->user();
            $tokenResult = $user->createToken('Personal Access Token');

            $token       = $tokenResult->token;
            if ($request->remember_me)
                $token->expires_at = Carbon::now()->addWeeks(1);
            $token->save();
            $data                 = [];
            $data['access_token'] = $tokenResult->accessToken;
            $data['token_type']   = 'Bearer';
            $data['expires_at']   = Carbon::parse(
                $tokenResult->token->expires_at
            )->toDateTimeString();
            ajaxReturn(200, '获取token成功', $data);

        }

        public function user(Request $request)
        {
            return response()->json($request->user());
        }
    }
